import {DownningState} from "../interfaces";
import weightState from "./2weight";
import readyState from "./0ready";
import settings from "../settings";
import player from "../player";
import state from "./state";
import controller from "../controller";
import plate from "../plate";
import weighter from "../weight";
import logger from "../logger";

class DownningStateImpl implements DownningState {
    name = "DownningState"
    minWeight = 150

    init() {
        this.minWeight = 150
    }

    leave(): void {
        player.clear();
    }

    plate(vehicleNumber: string, inout: string): void {
        if (settings.notZeroPlate) {
            player.say("磅众未归零识别车牌")
            state.stateContext = weightState;
            plate.emit(vehicleNumber, inout)
            controller.onlyCloseRL(inout === 'in' ? 2 : 1)
        }
    }

    _activeAndWeight2ReadyState() {
        // 是否根据红外判断是否结束上一辆车过磅流程，如果是，判断前后红外未遮挡时
        if (settings.active2ReadyState === true) {
            if (controller.R1 && controller.R2) {
                if (!state.isBack) {
                    controller.closeDownInout(state.inout);
                }
                logger.info("磅重已归零")
                state.stateContext = readyState;
            }
        } else {
            if (!state.isBack) {
                controller.closeDownInout(state.inout);
            }
            logger.info("磅重已归零")
            state.stateContext = readyState;
        }
    }

    active(R: boolean[]): void {
        if (weighter.weight <= 0.5) {
            this._activeAndWeight2ReadyState();
        }
    }

    weight_data(weight: number): void {
        if (weight <= 0.5) {
            this._activeAndWeight2ReadyState();
        } else if (settings.barrierGate !== 'inout') {
            if (this.minWeight > weight) {
                this.minWeight = weight
            } else if (this.minWeight + 3 < weight && settings.notZeroPlate) {
                // 如果重量大了，并且大于3吨，说明跟车了。不可能归0了，只能切换到称重模式
                player.say("磅众未归零，跟车上磅")
                controller.onlyCloseRL(state.inout === 'in' ? 2 : 1)
                state.stateContext = weightState;
                weighter.emit('weight_data', weight)
            }
        }
    }

    driverRequest(type: string): void {
    }

    do_weigh(weight: number, deductionWeight: number): void {
    }

}

const downningState = new DownningStateImpl();
export default downningState;
